#include "thread_pool.h"
#include "mysql/mysql.h"
#include "user.h"
extern ListNode * userList;

void userlogin1Command(task_t * task){
    //遍历用户链表找到
    ListNode * p = userList;
    while(p){
        //如果是同一个客户端的连接
        if(p->val->peerfd == task->peerfd && p->val->login_status == LOGIN_OUT){
            user_info * user = p->val;
            //strcpy(p->val->name,task->data);
            strcpy(user->name,task->data);
            login1(user);
            return;
        }else{
            p = p->next;
        }
    }
}

void userlogin2Command(task_t * task){
    ListNode * p = userList;
    while(p){
        //如果是同一个客户端的连接
        if(p->val->peerfd == task->peerfd && p->val->login_status == LOGIN_OUT){
            user_info * user = p->val;
            /* printf("encrypt:%s\n", p->val->encrypt); */
            /* strcpy(name,p->val->encrypt); */
            /* strcpy(user->encrypt,task->data); */
            login2(user, task->data);
            return;
        }else{
            p = p->next;
        }
    }
}

void get_setting(char *setting,const char * encrypt){
    int num = 0,i;
    for(i = 0;encrypt[i]!='\0';i++){
        if(num==4)break;
        if(encrypt[i]=='$'){
            num++;
        }
    }
    strncpy(setting,encrypt,i-1);
    setting[i] = '\0';
}

void login1(user_info * user){
    //接受client发送的用户名
        printf("enter login1\n");
        train_t t;
        memset(&t,0,sizeof(t));
        char *str[3] = {0};
        select_user(user,str);//把user_spwd换成通过MYSQL获得的encrypt
        if(str[0]){
            char encrypt[512] = {0};
            strcpy(encrypt,str[1]);
            //user记录用户名对应密文信息
            strcpy(user->name,str[0]);
            strcpy(user->encrypt,str[1]);
            //将encrypt切割出setting并发送给client端
            char setting[512] = {0};
            get_setting(setting,encrypt);
            t.len = strlen(setting);
            t.type = CMD_TYPE_LOGIN1_RIGHT;
            strcpy(t.buff,setting);
        }else{
            t.len = 0;
            t.type = CMD_TYPE_LOGIN1_ERROR;
        }
        sendn(user->peerfd,&t,8+t.len);
}
void login2(user_info * user,char *encrypt){
        printf("enter login2.\n");
        /* struct spwd* user_spwd = getspnam(name); */
        /* printf("login2 encrypt:%s\n", encrypt); */
        //对user中的密文进行对比分析
        train_t t;
        memset(&t,0,sizeof(t));
        if(!strcmp(encrypt, user->encrypt)){
            t.len = 0;
            t.type = CMD_TYPE_LOGIN2_RIGHT;
            user->login_status = LOGIN_ON;
            //查表获得user_id,更新user
            select_user_changeid(user);
        }else{
            t.len = 0;
            t.type = CMD_TYPE_LOGIN2_ERROR;
        }
        //发送给client端的回应
        int ret = sendn(user->peerfd,&t,8+t.len);
        printf("login2 ret: %d\n", ret);
        /* puts("1"); */
        /* printf("login2 send %d byte\n",ret); */
}
